<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编码" prop="billcode">
        <el-input
          v-model="queryParams.billcode"
          placeholder="请输入单据编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="billdate">
        <el-date-picker clearable size="small"
          v-model="queryParams.billdate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择单据日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户" prop="gid">
        <el-input
          v-model="queryParams.gid"
          placeholder="请输入客户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="billstate">
        <el-input
          v-model="queryParams.billstate"
          placeholder="请输入单据状态"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:waybill:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:waybill:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:waybill:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:waybill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="waybillList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="单据编码" prop="billcode" />
      <el-table-column label="单据日期" prop="billdate" width="180"/>
      <el-table-column label="客户" prop="gid" >
        <template slot-scope="scope">
          {{guesMatching(scope.row.gid)}}
        </template>
      </el-table-column>
      <el-table-column label="支付金额" prop="amount" />

      <el-table-column label="支付方式" prop="payid" >
        <template slot-scope="scope">
          {{payMatching(scope.row.payid)}}
        </template>
      </el-table-column>
      <el-table-column label="开单人" prop="empid" >
        <template slot-scope="scope">
          {{employeeMatching(scope.row.empid)}}
        </template>
      </el-table-column>
      <el-table-column label="司机" prop="driverid" >
        <template slot-scope="scope">
          {{driverMatching(scope.row.driverid)}}
        </template>
      </el-table-column>
      <el-table-column label="单据状态" prop="billstate" />
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:waybill:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:waybill:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改清运单主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编码" prop="billcode">
              <el-input v-model="form.billcode" placeholder="请输入单据编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开单人" prop="empid">
              <el-select v-model="form.empid" filterable  placeholder="请选择开单人" clearable size="small">
                <el-option
                  v-for="employee in employeeList"
                  :key="employee.empid"
                  :label="employee.name"
                  :value="employee.empid"
                />
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="选择订单" prop="empid">
              <el-select v-model="form.orderIdObject" value-key="billid" filterable  placeholder="请选择订单" clearable size="small" @change="changeOrder">
                <el-option
                  v-for="item in billList"
                  :key="item.billid"
                  :label="item.billcode"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="司机" prop="driverid">
              <el-select v-model="form.driverid" filterable  placeholder="请选择司机" clearable size="small" @change="form.tid=null">
                <el-option
                  v-for="driver in driverList"
                  :key="driver.empid"
                  :label="driver.name"
                  :value="driver.empid"
                />
              </el-select>
            </el-form-item>
          </el-col>
            <el-col :span="8">
            <el-form-item label="客户" prop="gid">
              <el-select v-model="form.gid" filterable  placeholder="请选择客户" clearable size="small" disabled>
                <el-option
                  v-for="guest in guestList"
                  :key="guest.gid"
                  :label="guest.name"
                  :value="guest.gid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入支付金额" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="8">
            <el-form-item label="支付方式" prop="payid">
              <el-select v-model="form.payid" filterable  placeholder="请选择支付方式" clearable size="small">
                <el-option
                  v-for="paymethod in paymethodList"
                  :key="paymethod.payid"
                  :label="paymethod.name"
                  :value="paymethod.payid"
                />
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="单据状态" prop="billstate">
              <el-input v-model="form.billstate" placeholder="请输入单据状态" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-alert
          v-if="arrears>0"
          :title="arrearsMsg"
          type="warning"
          closable
          show-icon>
        </el-alert>




        <el-divider content-position="center">派工单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddLWaybilldetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteLWaybilldetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="lwaybilldetailList" :row-class-name="rowLWaybilldetailIndex" @selection-change="handleLWaybilldetailSelectionChange" ref="lWaybilldetail">
          <el-table-column type="selection" width="50" />
          <el-table-column label="序号" prop="index" width="50"/>
          <el-table-column label="货品" prop="goodsid">
            <template slot-scope="scope">
              <el-select v-model="scope.row.goodsid" filterable  placeholder="请选择货品" clearable size="small">
                <el-option
                  v-for="goods in goodsList"
                  :key="goods.goodsid"
                  :label="goods.name+'('+goods.unitname+')'"
                  :value="goods.goodsid"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity">
            <template slot-scope="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入数量" @input="quantityChange($event,scope.$index)"/>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" placeholder="请输入单价" @input="scopeChange($event,scope.$index)"/>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount">
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount" placeholder="请输入金额" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWaybill, getWaybill, delWaybill, addWaybill, updateWaybill,getCode} from "@/api/system/waybill";
import {getPaymethodAll} from "@/api/system/paymethod";
import {listGuestAll} from "@/api/system/guest";
import {listDriverAll, listSalesmanAll} from "@/api/system/employee";
import {listGoodsAll} from "@/api/system/goods";
import {orderNotWaybillAll} from "@/api/system/orderbill";

export default {
  name: "Waybill",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedLWaybilldetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 清运单主表格数据
      waybillList: [],
      paymethodList:[],
      guestList:[],
      //货品列表
      goodsList: [],
      driverList:[],
      employeeList:[],
      // 派工单明细表格数据
      lwaybilldetailList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billcode: null,
        billdate: null,
        gid: null,
        amount: null,
        payid: null,
        empid: null,
        driverid: null,
        billstate: null,
      },
      billList:[],//选择订单下拉框
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billcode: [
          { required: true, message: "单据编码不能为空", trigger: "blur" }
        ],
        gid: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        payid: [
          { required: true, message: "支付方式不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
      },
      isUpdateAmount:false,//用来监听派单明细table变化时isUpdateAmount变化
      arrears:0,
      arrearsMsg:'',
    };
  },
  created() {
    this.getList();
    this.getPaymethodList();
    this.getGuesList();
    this.getDriverList();
    this.getGoodsList();
  },
  methods: {
    getGoodsList() {
      listGoodsAll().then(response => {
        this.goodsList = response.data;
      })
    },
    getPaymethodList(){
      getPaymethodAll().then(response => {
        this.paymethodList= response.data;
      })
    },
    getGuesList(){
      listGuestAll().then(response => {
        this.guestList = response.data;
      })
    },
    getDriverList() {
      listDriverAll().then(response => {
        this.driverList = response.data;
        this.getSalesmanList();
      });
    },
    getSalesmanList() {
      listSalesmanAll().then(response => {
        this.employeeList = response.data;
      });
    },
    //选择订单
    getOrderNotWaybillList(billid){
      orderNotWaybillAll({"billid":billid}).then(response=>{
        this.billList = response.data
      })
    },

    payMatching(payid){
      let name = "-";
      this.paymethodList.map(item => {
        if (payid == item.payid) {
          name = item.name;
          return
        }
      })
      return name;
    },
    guesMatching(gid) {
      let name = "-";
      this.guestList.map(item => {
        if (gid == item.gid) {
          name = item.name;
          return
        }
      })
      return name;
    },
    employeeMatching(employeeId) {
      let name = "-";
      this.employeeList.map(item => {
        if (employeeId == item.empid) {
          name = item.name;
          return
        }
      })
      return name;
    },

    driverMatching(employeeId) {
      let name = "-";
      this.driverList.map(item => {
        if (employeeId == item.empid) {
          name = item.name;
          return
        }
      })
      return name;
    },
    getCode(){
      getCode().then(response => {
        this.form.billcode= response.data;
      })
    },
    /** 查询清运单主列表 */
    getList() {
      this.loading = true;
      listWaybill(this.queryParams).then(response => {
        this.waybillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        billid: null,
        billcode: null,
        billdate: null,
        gid: null,
        amount: null,
        payid: null,
        empid: null,
        driverid: null,
        billstate: null,
        remark: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.arrears=null
      this.lwaybilldetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.billid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加清运单主";
      this.getOrderNotWaybillList(null);
      this.getCode();
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const billid = row.billid || this.ids
      await this.getOrderNotWaybillList(billid);
      getWaybill(billid).then(response => {
        this.form = response.data;
        this.billList.forEach(item=>{
          if(item.billid==this.form.orderid){
            this.form.orderIdObject=item;
            this.arrears=item.arrears;
            if(this.arrears>0){
              this.arrearsMsg=this.guesMatching(item.gid)+" 欠款："+item.arrears
            }
            return
          }
        })
        this.lwaybilldetailList = response.data.lwaybilldetailList;
       
        this.form.orderIdObject = this.billList.find(item=>item.billid  == response.data.orderid);
    //   console.log(this.billList.find(item=>item.billid  == response.data.orderid))
    //  console.log(this.billList[0].billid)
    //   console.log(response.data.orderid)
        this.open = true;
        this.title = "修改清运单主";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.lwaybilldetailList = this.lwaybilldetailList;
          if (this.form.billid != null) {
            updateWaybill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWaybill(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const billids = row.billid || this.ids;
      this.$modal.confirm('是否确认删除清运单主编号为"' + billids + '"的数据项？').then(function() {
        return delWaybill(billids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 清运单明细序号 */
    rowLWaybilldetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 清运单明细添加按钮操作 */
    handleAddLWaybilldetail() {
      let obj = {};
      obj.itemsno = "";
      obj.goodsid = "";
      obj.quantity = "";
      obj.price = "";
      obj.amount = "";
      obj.remark = "";
      this.lwaybilldetailList.push(obj);
    },
    /** 清运单明细删除按钮操作 */
    handleDeleteLWaybilldetail() {
      if (this.checkedLWaybilldetail.length == 0) {
        this.$modal.msgError("请先选择要删除的清运单明细数据");
      } else {
        const lwaybilldetailList = this.lwaybilldetailList;
        const checkedLWaybilldetail = this.checkedLWaybilldetail;
        this.lwaybilldetailList = lwaybilldetailList.filter(function(item) {
          return checkedLWaybilldetail.indexOf(item.index) == -1
        });
        this.isUpdateAmount = !this.isUpdateAmount;
      }
    },
    /** 复选框选中数据 */
    handleLWaybilldetailSelectionChange(selection) {
      this.checkedLWaybilldetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/waybill/export', {
        ...this.queryParams
      }, `waybill_${new Date().getTime()}.xlsx`)
    },
    //派单明细数量输入框事件
    quantityChange(value,index){
      let item = this.lwaybilldetailList[index];
      //单价不为空
      item.price && (item.amount = value*item.price) && (this.isUpdateAmount = !this.isUpdateAmount)

    },
    //派单明细单价输入框事件
    scopeChange(value,index){
      let item = this.lwaybilldetailList[index];
      //数量不为空
      item.quantity && (item.amount = value*item.quantity) && (this.isUpdateAmount = !this.isUpdateAmount);

    },
    changeOrder(data){
      this.form.orderid=this.form.orderIdObject.billid;
      this.form.gid=data.gid;
      //清空
     this.lwaybilldetailList = []
      let total=data.goodsPrice*data.quantity;
      this.lwaybilldetailList.push({"goodsid":data.goodsid,"quantity":data.quantity, "price":data.goodsPrice, "amount": total})
      this.isUpdateAmount = !this.isUpdateAmount
      this.arrears=data.arrears;
      if(this.arrears>0){
        this.arrearsMsg=this.guesMatching(data.gid)+" 欠款："+data.arrears
      }
    }
  },
  watch:{
    isUpdateAmount: function (newVal, oldVal) {
        if(this.lwaybilldetailList.length == 0){
          this.form.amount = 0;
          return false
        }
        let cumsum = 0;
        const newData = this.lwaybilldetailList.map(({goodsid, quantity, price,amount}) => ({goodsid, quantity, price,amount,total_amount: cumsum += amount}));
        this.form.amount = newData[newData.length-1].total_amount;

    },

  }
};
</script>
